package com.zst.common.buffer;

import com.zst.common.buffer.partition.Partitioner;

import java.util.ArrayList;
import java.util.List;

public class MultiChannelBuffer<T> {
    private final Buffer<T>[] buffers;
    private Partitioner partitioner;

    public MultiChannelBuffer(int bufferSize, int partitionNum, Partitioner partitioner) {
        buffers = new Buffer[partitionNum];
        for (int i = 0; i < partitionNum; i++) {
            buffers[i] = new Buffer<>(bufferSize);
        }
        this.partitioner = partitioner;
    }

    public boolean save(T data) {
        int partition = partitioner.partition(buffers.length);
        return buffers[partition].add(data);
    }

    public List<T> consume(int bufferIndex) {
        List<T> buffer = new ArrayList<>();
        buffers[bufferIndex].drainTo(buffer);
        return buffer;
    }
}
